package cn.alise.interceptor;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.alise.consts.BaseConsts;
import cn.alise.enums.EnumClass;
import cn.alise.qdp.model.log.UserAccessLogs;
import cn.alise.qdp.model.user.User;
import cn.alise.qdp.service.log.UserAccessLogsService;

/**
 * 操作日志记录
 * @author CHENH
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private UserAccessLogsService userAccessLogsService;

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		if (userAccessLogsService == null) {//解决service为null无法注入问题 
	        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
	        userAccessLogsService = (UserAccessLogsService) factory.getBean("userAccessLogsService");
	    }
		
		// session中获取人员信息
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(BaseConsts.IUser.USER_SESSION_KEY);
		
		// 请求的URL
		String url = request.getRequestURI();
		
		if (user!=null) {
			// 保存日志
			UserAccessLogs userAccessLogs = new UserAccessLogs();
			userAccessLogs.setUserId(user.getUserId());
 	 		userAccessLogs.setUserName(user.getUserName());
 	 		userAccessLogs.setAccount(user.getAccount());
 	 		userAccessLogs.setRoleName(user.getRoleNameArr());
 	 		userAccessLogs.setIpaddress(getIpAddress(request));
 	 		userAccessLogs.setPath(url);
 	 		userAccessLogs.setType(EnumClass.LogOperation.HANDEL.getKey());
			userAccessLogs.setCreatedTime(new Timestamp(System.currentTimeMillis()));
			
			this.userAccessLogsService.save(userAccessLogs);
		}
		
		super.afterCompletion(request, response, handler, ex);
	}
	
	/**
	 * 获取ip地址
	 */
	public static String getIpAddress(HttpServletRequest request) { 
	    String ip = request.getHeader("x-forwarded-for"); 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_CLIENT_IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	  }
}